package com.h4313.ghome.ui.fragments;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.h4313.ghome.GHomeApplication;
import com.h4313.ghome.R;
import com.h4313.ghome.io.CapteurChoiceTask;
import com.h4313.ghome.io.CapteurChoiceTask.CapteurChoiceCallback;
import com.h4313.ghome.utils.UIUtils;

public class CapteurChoiceFragment extends Fragment implements
		CapteurChoiceCallback, View.OnClickListener {

	public static final String TEACH_URL = GHomeApplication.SERVER_URL
			+ "/teachin/%s";

	protected Spinner spinnerType;
	protected Button btTeach;
	protected TextView tvOK;
	protected ProgressBar progress;

	@Override
	public void onClick(View v) {

		if (v.getId() == R.id.bt_teach) {
			String typeSelectionne = (String) spinnerType.getSelectedItem();
			// Changer URL
			String stringUrl = String.format(TEACH_URL, typeSelectionne);
			Activity activity = this.getActivity();
			ConnectivityManager connMgr = (ConnectivityManager) activity
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

			if (networkInfo != null && networkInfo.isConnected()) {

				// TODO remettre ici la roue de chargement

				CapteurChoiceTask task = new CapteurChoiceTask(this);
				progress.setVisibility(View.VISIBLE);
				task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, stringUrl);
			} else {
				System.out.print("No Network available");
			}

		}

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_capteur_choice, container,
				false);

		spinnerType = (Spinner) v.findViewById(R.id.spinner_type_capteur);
		btTeach = (Button) v.findViewById(R.id.bt_teach);
		btTeach.setOnClickListener(this);
		tvOK = (TextView) v.findViewById(R.id.tv_ok);
		progress = (ProgressBar) v.findViewById(R.id.progressBar_choice);

		return v;

	}

	@Override
	public void onCapteurTypeFound(String capteurType) {

		progress.setVisibility(View.GONE);

		if (!TextUtils.isEmpty(capteurType) && "OK".equals(capteurType)) {
			UIUtils.showToast(this, "Teachin réalisé avec succès !",
					Toast.LENGTH_SHORT);
		} else if ("already_teaching".equals(capteurType)) {
			UIUtils.showToast(this, "Un teachin est déjà en cours.",
					Toast.LENGTH_SHORT);
		}else {
			UIUtils.showToast(this, "Impossible de réaliser le teachin",
					Toast.LENGTH_SHORT);
		}
	}

}
